<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/29/0029
 * Time: 11:02
 */

namespace app\sports_admin\controller;


class ClearCache extends Base
{
    protected $beforeActionList = [
        'isAdmin'=>['only'=>'clear,delete_dir_file']
    ];
    //清理缓存首页
    public function index()
    {
        return view('index');
    }
    /**
     * 清除缓存操作
     * @param $type 清除缓存
    */
    public function clear() {
        if ($this->delete_dir_file(CACHE_PATH) || $this->delete_dir_file(TEMP_PATH)) {
            return json(['code'=>204,'msg'=>'清除成功']);
        } else {
            return json(['errorCode'=>205,'msg'=>'清除失败']);
        }
    }


    /**
     * 循环删除目录和文件
     * @param string $dir_name
     * @return bool
     */
    function delete_dir_file($dir_name)
    {
        $result = false;
        if (is_dir($dir_name)) {
            if ($handle = opendir($dir_name)) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != '.' && $item != '..') {
                        if (is_dir($dir_name . DS . $item)) {
                            $this->delete_dir_file($dir_name . DS . $item);
                        } else {
                            unlink($dir_name . DS . $item);
                        }
                    }
                }
                closedir($handle);
                if (rmdir($dir_name)) {
                    $result = true;
                }
            }
        }
        return $result;
    }
}